package com.guo.pet_store.admin.service;

import com.guo.pet_store.admin.Utils.MyBeanUtils;
import com.guo.pet_store.admin.dao.UserRepository;
import com.guo.pet_store.admin.pojo.User;
import javassist.NotFoundException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Optional;

@Service
public class UserServiceImpl implements UserService{
    @Autowired
    UserRepository userRepository;
    public User checkUser(String username,String password){
        User user =userRepository.findUserByUsernameAndPassword(username,password);
        if (user !=null){
            return user;
        }else {
            return null;
        }
    }

    @Override
    public Page<User> listUser(Pageable pageable) {
        return userRepository.findAll(pageable);
    }

    @Override
    public User addUser(User user) {
        userRepository.save(user);
        return user;
    }

    @Override
    public User selectAUser(Long userId) {
        return userRepository.getOne(userId);
    }

    @Transactional
    @Override
    public User updateUser(User oldUser,Long userId) {
            User user = userRepository.getOne(userId);
            BeanUtils.copyProperties(oldUser,user, MyBeanUtils.getNullPropertyNames(oldUser));
            return userRepository.save(user);
        }

    @Override
    public User getUserByName(String username) {
        return userRepository.findUserByUsername(username);
    }

    @Override
    public void changMoney(Double money, Long userId) {
        userRepository.changeMoney(money,userId);
    }

//    判断用户是否已经存在
    @Override
    public Boolean isUsed(String username) {
        if (userRepository.findUserByUsername(username) != null)
            return true;
        else return false;
    }

}
